package com.foxit.pdf2html5.web.controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxit.pdf2html5.web.common.Config;

@Controller
@Scope("prototype")
public class GetDocBinController{
	private static final Logger  log = Logger.getLogger(GetDocBinController.class);
	
	private String docId = "";
	
	private HttpServletRequest httpRequest;
	
	private HttpServletResponse httpResponse;
	
	
	
	@RequestMapping(value = "/GetDocBin.do")
	public void GetDocBin(HttpServletRequest request,HttpServletResponse response) throws IOException 
	{
		this.httpRequest = request;
		this.httpResponse = response;
		this.docId = request.getParameter("fileid");
		if(this.docId == null) return;
		
		String tempFilePath = this.httpRequest.getSession().getServletContext().getRealPath("temp");
		
		String tempPath = tempFilePath + File.separator + this.docId + File.separator + "docBin" + File.separator;
		String filePath = tempPath + "doc.bin";
		System.out.println(filePath);
		System.out.println(new File(filePath).exists());
		DataInputStream dis=new DataInputStream(new FileInputStream(new File(filePath)));
		int size=dis.available();
		byte[] str = new byte[size]; 
		for(int i=0;i<size;i++){
			str[i] = (byte)dis.read();
		}
		this.writeImgStreamToClient(str);
	}
	 private void writeImgStreamToClient(byte[] binData) throws IOException
     {
        
		 this.httpResponse.setContentType("text/html");
		 Date now = new Date();  
     	 this.httpResponse.setDateHeader("Last-Modified",now.getTime());  
 		 this.httpResponse.setDateHeader("Expires", 0);        	  
		 this.httpResponse.addHeader( "Cache-Control", "no-cache" );  
		 this.httpResponse.addHeader( "Cache-Control", "must-revalidate" ); 
		 this.httpResponse.addHeader("ETag",String.valueOf(now.getTime()));
		 this.httpResponse.setContentLength(binData.length);
     	ServletOutputStream out = this.httpResponse.getOutputStream();
		out.write(binData);
		out.flush();
		out.close();
     }
}
